package com.ruicar.afs.cloud.batch.frame.control;

import com.ruicar.afs.cloud.batch.enums.MessageType;
import com.ruicar.afs.cloud.batch.frame.AbsBatchRunner;
import com.ruicar.afs.cloud.batch.frame.logger.WsMonitorHelper;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.text.MessageFormat;
import java.util.List;

@Slf4j
public class AfsStepRunnerExceptionHandler implements Thread.UncaughtExceptionHandler{
    @Setter
    private List<AbsBatchRunner> absBatchRunners;
    private Throwable throwable;
    @Override
    public void uncaughtException(Thread t, Throwable e) {
        if(this.throwable==null&&!(e instanceof InterruptedException)) {
            this.throwable = e;
            for (AbsBatchRunner absBatchRunner:absBatchRunners){
                if(!StringUtils.equals(absBatchRunner.getName(),t.getName())){
                    if(!absBatchRunner.isFinished()) {
                        log.info("终止线程{}",absBatchRunner.getName());
                        absBatchRunner.interrupt();
                        WsMonitorHelper.sendMessage(MessageType.ERROR, MessageFormat.format("线程{0}出错，终止同组线程{1}",t.getName(),absBatchRunner.getName()));
                    }
                }
            }
        }
    }
}
